<template>
    <div style="height: 100%;width: 100%">
        <tiny-editor ref="tinymce" v-model="localValue" :init='init'
                     @input="handleInput"></tiny-editor>
        <a-modal
            title="Title"
            :visible="visible"
            :zIndex="2000"
            @ok="handleOk"
            @cancel="handleCancel"
        >
            <a-form layout="inline">
                <a-row :gutter="24">
                    <a-col :span="12">
                        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="纸张设置">
                            <a-select v-model="paperType" :getPopupContainer="(p)=>p.parentNode" @change="changeSelect">
                                <a-select-option value="A3">A3</a-select-option>
                                <a-select-option value="A4">A4</a-select-option>
                                <a-select-option value="A5">A5</a-select-option>
                                <a-select-option value="B3">B3</a-select-option>
                                <a-select-option value="B5">B5</a-select-option>
                                <a-select-option value="Custom">自定义</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="方向">
                            <a-radio-group v-model="direction" @change="changGroup">
                                <a-radio-button value="cross">
                                    纵向
                                </a-radio-button>
                                <a-radio-button value="longitudinal">
                                    横向
                                </a-radio-button>
                            </a-radio-group>
                        </a-form-item>
                    </a-col>
                </a-row>
                <a-row :gutter="24">
                    <a-col :span="12">
                        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="宽">
                            <a-input-number :disabled="paperType!='Custom'" v-model="paperWidth" :min="1"/>
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="高">
                            <a-input-number :disabled="paperType!='Custom'" v-model="paperHeight" :min="1"/>
                        </a-form-item>
                    </a-col>
                </a-row>
            </a-form>
        </a-modal>
    </div>
</template>

<script>
import editor from '@tinymce/tinymce-vue';
import SysFileApi from '@/api/system/core/sysFile'
import {Util,TokenUtil} from "@lowcode/jpaas-common-lib"

export default {
    name: 'myEditor',
    props: ['value', 'setting','paper'],
    data() {
        return {
            localValue: '',
            init: { // 配置信息
                language_url: require('@public/tinymce/langs/zh-Hans.js'), // 中文包的存放路径
                language: 'zh-Hans',
                toolbar_mode: 'sliding',
                plugins: 'print fullscreen code table  link table image ', //插件配置
                toolbar: "btnContainer btnPaper image  | code undo redo restoredraft bold italic underline strikethrough fontselect fontsizeselect| alignleft aligncenter alignright alignjustify alignnone | fullscreen print inserttable tablemergecells tablesplitcells",
                //禁用blob类型使用base 存储图片
                images_dataimg_filter: function(img) {
                    return img.hasAttribute('internal-blob');
                },
                extended_valid_elements: 'tr[class|rx-list]',

                images_upload_handler: function (blobInfo, succFun, failFun) {
                    var file = blobInfo.blob();//转化为易于理解的file对象
                    let formData = new FormData();
                    formData.append('files', file, file.name);//此处与源文档不一样

                    SysFileApi.upload(formData).then(res => {
                        if (!res.success) {
                            return;
                        }
                        var fileId = res.data[0].fileId;
                        fileId = Util.encryptWord(fileId);
                        let token = TokenUtil.getToken();
                        let url = `/api/api-system/system/core/sysFile/previewImg?fileId=${fileId}&accessToken=${token}`
                        succFun(url);
                    });
                },

                setup: (editor) => {
                    let self = this;
                    editor.ui.registry.addButton('btnPaper', {
                        text: '纸张',
                        onAction: () => {
                            this.onCustomStyleButtonClick(editor)
                        },
                    });
                    editor.ui.registry.addButton('btnContainer', {
                        text: '容器',
                        onAction: () => {
                            this.containerButtonClick(editor)
                        },
                    });


                    //添加删除按钮
                    editor.ui.registry.addButton('btnDel', {
                        tooltip:'删除',
                        icon: 'table-delete-table', // 替换为你的图标名称
                        onAction: function (node) {
                            var editor = tinymce.activeEditor; // 获取当前活动的编辑器实例
                            var selection = editor.selection; // 获取当前选中的元素
                            // 检查是否有选中元素
                            self.$emit('CustomButton', 'delete')
                            if (selection && selection.getContent()) {
                                // 执行删除选中元素的逻辑
                                selection.setContent('');
                            }
                        }
                    });
                    //添加编辑按钮
                    editor.ui.registry.addButton('btnEdit', {
                        tooltip: '编辑',
                        icon:'edit-block',
                        onAction: function () {
                            self.$emit('CustomButton', '')
                        }
                    });
                    //add添加自定义定制按钮
                    editor.ui.registry.addContextToolbar('QrImg', {
                        predicate: function (node) {
                            if (node.id && node.id.includes('container')) {
                                return true
                            }
                            return node.nodeName.toLowerCase() === 'img' && node.id
                        },
                        items: 'btnDel btnEdit',
                        position: 'node',
                        scope: 'node'
                    });
                    editor.on('click', function(e) {
                        // 获取选中的容器添加样式
                        self.handleClick(e)
                        let iframeDoc = self.getIframeDocument();
                        if (!iframeDoc || !e.target.id.includes('container')) {
                            return null;
                        }
                        let style = iframeDoc.getElementById(e.target.id).style;
                        self.containerId = e.target.id
                        style.border = '2px dotted #1890ff'
                    });
                    editor.on('selectionchange', function(e) {
                        // 取消选中容器添加样式
                        let iframeDoc = self.getIframeDocument();
                        if (!iframeDoc || !self.containerId) {
                            return null;
                        }
                        let style = iframeDoc.getElementById(self.containerId).style;
                        style.border = self.setting.borderWidth+'px solid '+self.setting.borderColor
                    });
                },
            },
            visible: false,
            paperWidth: 210,
            paperHeight: 297,
            paperType: 'A4',
            labelCol: {span: 8},
            wrapperCol: {span: 15},
            direction: 'cross',

            //尺寸大小
            sizeMap: {
                "A3": {width: 297, height: 420},
                "A4": {width: 210, height: 297},
                "A5": {width: 148, height: 210},
                "B3": {width: 353, height: 500},
                "B5": {width: 176, height: 250}
            },
            containerId:0,
        };
    },
    components: {
        'tiny-editor': editor,
    },
    mounted(){

        this.$nextTick(() => {
            // 获取编辑器实例
            if(this.paper){
                //设置纸张
                this.paperType = this.paper.paperType;
                this.paperWidth = this.paper.paperWidth;
                this.paperHeight = this.paper.paperHeight;
                this.direction = this.paper.direction;

            }
            setTimeout(() => {
                this.localValue =this.value;
                this.tinymceInit();
                this.paperSize();
                this.changGroup()
            }, 500);
        });

    },

    methods: {
        containerDelete(id) {
            if (id.includes('container')) {
                let iframeDoc = this.getIframeDocument();
                let element = iframeDoc.getElementById(id);
                element.parentNode.removeChild(element);
            }
        },
        //初始化默认高度自适应
        tinymceInit() {
            // 获取编辑器实例
            const editor = this.$refs.tinymce.editor;
            if (!editor && !editor.getContainer()) {
                return;
            }
            // 设置编辑器容器高度为自动
            const editorContainer = editor.getContainer();
            if(editorContainer && editorContainer.style){
                editorContainer.style.height = '100%';
            }
        },
        paperSize(name) {
            let style = this.tinymceStyle();
            if (!style) {
                return;
            }
            style.width =  this.paperWidth+'mm';
            style.height = this.paperHeight+'mm';
            style.padding = '10mm 10mm 10mm 10mm !important';
            style.margin = '20px auto';
            style.background = 'white';
            style.minHeight = '100%';
            style.boxSizing = ' border-box';
            style.boxShadow = '0 2px 12px 0 rgb(0 0 0 / 10%)';
            style.position = 'relative';
            style.padding = '20px';
        },
        //自定义点击事件A4
        onCustomStyleButtonClick(editor) {
            this.visible = true;
        },
        //点击容器
        containerButtonClick() {
            let id = 'container' + Util.randomId();
            let html = `<div id='${id}' style='position:relative;margin-right:5mm;margin-left:5mm;margin-top:5mm;border: 1px solid #dcd9d9;border-radius: 5px;padding: 10px 10px 30px 10px;width: 100mm;height: 50mm'></div>
                        <p></p>
                        `;
            this.insertContent(html)
            let container = {
                id: id,
                type: 'container',
                top: 5,
                right: 5,
                left: 5,
                width: 100,
                height: 50,
                textAlign: 'left',
                borderColor: '#dcd9d9',
                borderWidth:1,
                borderCorner:3,
                position:'relative',
                paddingLeft:10,
                paddingTop:10,
                paddingBottom:10,
                paddingRight:10


            }
            this.$emit('addContainer', container)
        },
        //输入触发事件
        handleInput(event) {
            // 处理输入事件
            this.$emit('input', event)
        },
        // 在光标位置插入文本
        insertContent(html) {
            const editor = this.$refs.tinymce.editor;
            editor.insertContent(html);
        },
        handleOk() {
            this.visible = false
        },
        handleCancel() {
            this.visible = false
        },
        changeSelect() {
            let sizeObj = this.sizeMap[this.paperType];
            this.paperWidth = sizeObj.width;
            this.paperHeight = sizeObj.height;
        },
        changGroup() {
            let style = this.tinymceStyle();
            if (!style) {
                return null;
            }
            if (this.direction == 'cross') {
                style.width = this.paperWidth + 'mm';
                style.height = this.paperHeight + 'mm';
            } else {
                style.width = this.paperHeight + 'mm';
                style.height = this.paperWidth + 'mm';
            }
        },
        //点击获取光标
        handleClick(event) {
            let id = event.target.id;
            if (id) {
                this.$emit('rxEditor', id)
            }
        },
        //获取样式
        tinymceStyle() {
            let iframeDoc = this.getIframeDocument();
            if (!iframeDoc) {
                return null;
            }
            let style = iframeDoc.getElementById('tinymce').style;
            return style;
        },
        /**
         * 获取编辑器的document 对象 。
         * @returns {Document}
         */
        getIframeDocument() {
            const editor = this.$refs.tinymce.editor;
            if (!editor) {
                return null;
            }
            const editorContainer = editor.getContainer();
            if (!editorContainer) {
                return null;
            }

            return editorContainer.querySelector("iframe").contentWindow.document;
        },
    },
    watch: {
        paperWidth() {
            let style = this.tinymceStyle();
            if (style) {
                style.width = this.paperWidth + 'mm';
            }

        },
        paperHeight() {
            let style = this.tinymceStyle();
            if (style) {
                style.height = this.paperHeight + 'mm';
            }
        },
        value(val) {
            this.localValue = val;
        },
        setting: {
            //修改样式
            handler() {
                let document = this.getIframeDocument()
                let style = document.getElementById(this.setting.id).style;
                if (this.setting.type == 'container') {
                    if (this.setting.textAlign != 'center') {
                        style.marginLeft = this.setting.left + 'mm';
                        style.marginRight = this.setting.right + 'mm';
                    }
                    style.width = this.setting.width + 'mm';
                    style.height = this.setting.height + 'mm';
                    if (this.setting.textAlign == 'center') {
                        style.float = 'initial';
                        style.margin = 'auto'
                    } else if (this.setting.textAlign == 'left') {
                        style.float = 'left'
                        delete style.margin;
                    } else if (this.setting.textAlign == 'right') {
                        style.float = 'right'
                        delete style.margin;
                    }
                    style.position = this.setting.position;
                    style.border = this.setting.borderWidth+'px solid '+this.setting.borderColor;
                    style.borderRadius = this.setting.borderCorner+'px'
                    style.marginTop = this.setting.top + 'mm';
                    style.padding =this.setting.paddingTop+'px '+this.setting.paddingRight+'px '+this.setting.paddingBottom+'px '+this.setting.paddingLeft+'px';

                } else {
                    if (this.setting.cross == 'right') {
                        style.right = this.setting.crossNumber + 'mm';
                        style.left ='auto';
                    } else {
                        style.left = this.setting.crossNumber + 'mm';
                        style.right = 'auto';
                    }
                    if (this.setting.anyway == 'top') {
                        style.top = this.setting.anywayNumber + 'mm';
                        style.bottom ='auto';
                    } else {
                        style.bottom = this.setting.anywayNumber + 'mm';
                        style.top ='auto';
                    }
                    if (this.setting.type == "qrcode") {
                        style.width = style.height = this.setting.size + 'px';
                    } else {
                        style.width = this.setting.width + 'px';
                        style.height = this.setting.height + 'px';
                    }
                }

                let html = document.getElementById('tinymce').innerHTML;
                this.$emit('input', html)
            },
            deep: true
        },
    }
}
</script>
<style>

</style>